package com.tech.zhidengxian.service.impl;

import com.tech.zhidengxian.mapper.ChatMapper;
import com.tech.zhidengxian.model.dataobject.ChatDO;
import com.tech.zhidengxian.model.dataobject.MessageDO;
import com.tech.zhidengxian.model.dto.ChatDTO;
import com.tech.zhidengxian.model.dto.MessageDTO;
import com.tech.zhidengxian.service.api.ChatService;
import com.tech.zhidengxian.util.JacksonUtils;
import com.tech.zhidengxian.util.TimeUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class ChatServiceImpl implements ChatService {
    @Resource
    private ChatMapper chatMapper;
//    @Override
    public ChatDTO creatChat(ChatDTO chatDTO) {
        chatDTO.setCreateTime(TimeUtil.currentDate());
        chatDTO.setUpdateTime(TimeUtil.currentDate());
        chatDTO.setIsDeleted(false);
        MessageDTO messageDTO = new MessageDTO();
        messageDTO.setCreateTime(TimeUtil.currentDate());
        chatDTO.setGid(chatDTO.getGoodsInfo().getId());
        chatDTO.setName(chatDTO.getCreatorInfo().getUsername()+"_"+chatDTO.getReceiverInfo().getUsername());
        chatDTO.setLastMessage(messageDTO);
        ChatDO chatDO = JacksonUtils.convert(chatDTO,ChatDO.class);
        chatMapper.creatChat(chatDO);
        chatDTO.setId(chatDO.getId());
        return chatDTO;
    }

    @Override
    public int refreshLastMsg4Chat(ChatDTO chatDTO) {
        ChatDO chatDO = JacksonUtils.convert(chatDTO,ChatDO.class);
        return chatMapper.refreshLastMsg4Chat(chatDO);
    }

    @Override
    public List<ChatDTO> queryChatListByUid(Long uid) {
        List<ChatDO> chatDOS = chatMapper.queryChatListByUid(uid);
        List<ChatDTO> chatDTOList = JacksonUtils.convertList(chatDOS, ChatDTO.class);
        chatDTOList.forEach(chatDTO -> {
            chatDTO.setNickInfo(uid.equals(chatDTO.getCreatorId())?chatDTO.getReceiverInfo():chatDTO.getCreatorInfo());
        });
        return chatDTOList;
    }

    @Override
    public ChatDTO createOrLoadChat(ChatDTO chatDTO) {
        ChatDO chatDO = JacksonUtils.convert(chatDTO, ChatDO.class);
        ChatDO chat = chatMapper.loadChat(chatDO);
        if (chat == null) {
            chatDTO = creatChat(chatDTO);
        }else {
            chatDTO = JacksonUtils.convert(chat, ChatDTO.class);
        }
        chatDTO.setNickInfo(chatDTO.getReceiverInfo());
        return chatDTO;
    }


}
